//
//  ViewController.m
//  HybridBridge
//
//  Created by 文道江 on 15/11/20.
//  Copyright © 2015年 文道江. All rights reserved.
//

#import "ViewController.h"
#import "UpgradeManger.h"
#import "WebViewController.h"
#import "ChatVideoController.h"

#import <GCDWebServer.h>

@interface ViewController ()

@property (strong, nonatomic) NSString *openUrl;
@property (strong, nonatomic) WVJB_WEBVIEW_TYPE *webView;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) GCDWebServer *webServer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setUserAgent];

    //设置默认加载URL
    //self.url = [NSURL URLWithString:[@"file://" stringByAppendingFormat:@"%@", [FZEasyFile fullFileName:@"web/index.html"]]];
    self.url = [NSURL URLWithString:[UpgradeManger getWebAppUrl]];
//    self.url = [NSURL URLWithString:@"http://192.168.1.115:8080/"];
    // Do any additional setup after loading the view, typically from a nib.


//    WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
//    theConfiguration.allowsAirPlayForMediaPlayback = YES;
//    theConfiguration.requiresUserActionForMediaPlayback = YES;

    _webView = [[WKWebView alloc]initWithFrame:self.view.frame];
    _webView.scrollView.bounces = NO;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _webView.scrollView.scrollEnabled = NO;
    HybridBridge *bridge = [HybridBridge bridgeForWebView:_webView webViewDelegate:self controller:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"........... %@", data);
    }];

    // 加载插件
    //[bridge loadPlugin:@"BaiduMTJ"];
    [bridge loadPlugin:@"Social"];
    [bridge loadPlugin:@"GeTui"];
    //[bridge loadPlugin:@"Agora"];
    [bridge loadPlugin:@"UpgradeSplash"];

    [self subscribePushMessage]; //处理推送消息


    [self.view addSubview: _webView];
    
    _webServer = [[GCDWebServer alloc] init];
    NSString *dir = [[[UpgradeManger getWebAppUrl] stringByReplacingOccurrencesOfString:@"file://" withString:@""] stringByReplacingOccurrencesOfString:@"index.html" withString:@""];
    [_webServer addGETHandlerForBasePath:@"/" directoryPath:dir indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
    [_webServer startWithPort:8090 bonjourName:nil];
    
    [NSThread sleepForTimeInterval:0.2];
    if (_openUrl == nil){
        [self loadWebApp];
    }else{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_openUrl]];
        [_webView loadRequest:request];
    }


#ifdef DEBUG
    [KSToastView ks_showToast:@"Run in debug mode"];
#endif

}


- (UIStatusBarStyle)preferredStatusBarStyle {
    //return UIStatusBarStyleLightContent;
    return UIStatusBarStyleDefault;
}


- (void)loadWebApp {

    /*if (![FZEasyFile isFileExists:@"web/webapp_version.txt"]){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"web" ofType:@"zip"];
        if (path)[SSZipArchive unzipFileAtPath:path toDestination:[FZEasyFile fullFileName:@"web"]];
    }*/
    //[self loadURL:self.url];
//    [self.webView loadFileURL:self.url allowingReadAccessToURL: self.url];
    [self loadURL:[NSURL URLWithString:@"http://localhost:8090/index.html"]];
}

- (void)loadURL:(NSURL *)url{
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)loadHybridUrl:(NSString *)act{
    NSLog(@"%@",@"loadHybridUrl");
    _openUrl = [[self.url.absoluteString stringByAppendingString:@"#"] stringByAppendingString:act];
    NSURL *requestUrl = [NSURL URLWithString: _openUrl];
    NSLog(@"%@",_openUrl);
    NSURLRequest *requestHybridUrl = [NSURLRequest requestWithURL:requestUrl];
    [_webView loadRequest:requestHybridUrl];
}

- (NSString*) setUserAgent{
    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

    NSString *userAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU %@ %@ like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/%@ MSNative %@", device.name, device.systemName,device.systemVersion, device.systemVersion, infoDictionary[@"CFBundleShortVersionString"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
    return userAgent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    if(_webServer != nil){
        [_webServer stop];
        _webServer = nil;
    }
}

#pragma mark 处理推送离线推送消息

- (void)subscribePushMessage{

    [[HybridEventBus defaultEventBus] subscribe:@"GeTuiSdkDidReceivePayload" UsingBlock:^(NSNotification *notification) {

        NSString *payloadMsg = notification.userInfo[@"payloadMsg"];

        //只处理离线消息
        if (notification.userInfo && [notification.userInfo[@"offLine"] boolValue]){

            NSLog(@"payload %@", notification.userInfo);
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];

            dispatch_async(dispatch_get_main_queue(), ^(){

                // 处理带 CMD 的推送消息
                if (dictionary && dictionary[@"cmd"]){

                    NSString *cmd = dictionary[@"cmd"];
                    if ([cmd isEqualToString:@"hybrid"]){

                        _openUrl = [[self.url.absoluteString stringByAppendingString:@"#"] stringByAppendingString:dictionary[@"act"]];
                    }else if ([cmd isEqualToString:@"url"]){

                        WebViewController *webViewController = [[WebViewController alloc] init];
                        [webViewController setOpenUrl:dictionary[@"act"]];
                        if (self.navigationController){
                            [self.navigationController pushViewController:webViewController animated:YES];
                        }else{
                            [self presentViewController:webViewController animated:YES completion:nil];
                        }
                    }
                }
            });
        }

    }];
}
@end
